<template>
  <div class="page-header-index-wide" :style="{ minHeight: `${layoutContentHeight - pageHeaderHeight - 24}px` }">
    <a-spin :spinning="loading || partyLoading">
      <a-card :bordered="false" :bodyStyle="{ padding: '16px 0', height: '100%' }" :style="{ height: '100%' }">
        <div class="account-settings-info-main">
          <div class="account-settings-info-left">
            <div class="account-settings-info-view">
              <a-form :form="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                <a-form-item :label="$t('authenticationCenter.org.personName')">
                  <span>{{ user.name }}</span>
                </a-form-item>
                <a-form-item :label="$t('authenticationCenter.org.gender')">
                  <span>{{ user.gender | genderFilter }}</span>
                </a-form-item>
                <a-form-item :label="$t('authenticationCenter.org.username')">
                  <span>{{ user.username }}</span>
                </a-form-item>

                <a-form-item :label="$t('authenticationCenter.org.dept')">
                  <div class="org-name-tree" v-for="item in orgMatched" :key="item.id" :title="item.orgNames">
                    <a-tag v-if="item.id === user.orgId">{{ $t('common.main') }}</a-tag
                    >{{ item.orgNames }}
                  </div>
                </a-form-item>
                <a-form-item :label="$t('authenticationCenter.org.position')">
                  <span>{{ user.position }}</span>
                </a-form-item>
                <a-form-item :label="$t('authenticationCenter.org.identity')">
                  <span>{{ $t(identityTypeMap[user.identityType]) }}</span>
                </a-form-item>
                <a-form-item v-if="user.identityType === 'HIGHER'" :label="$t('authenticationCenter.org.manageOrg')">
                  <div class="org-name-tree" v-for="item in manageOrgMatched" :key="item.id" :title="item.orgNames">
                    {{ item.orgNames }}
                  </div>
                </a-form-item>
                <a-form-item :label="$t('authenticationCenter.org.higherUp')">
                  <span>{{ user.higherName }}</span>
                </a-form-item>

                <a-form-item :label="$t('authenticationCenter.org.jobNumber')">
                  <span>{{ user.jobNumber }}</span>
                </a-form-item>
                <a-form-model-item :label="$t('authenticationCenter.org.englishName')">
                  <span>{{ user.englishName }}</span>
                </a-form-model-item>
                <a-form-model-item :label="$t('authenticationCenter.org.mobile')">
                  <span>{{ user.mobile | phoneFilter(user.phoneRegion) }}</span>
                </a-form-model-item>
                <a-form-item :label="$t('authenticationCenter.org.phoneNumber')">
                  <span>{{ user.telephone }}</span>
                </a-form-item>
                <a-form-item :label="$t('authenticationCenter.org.email')">
                  <span>{{ user.email }}</span>
                </a-form-item>
                <a-form-item :label="$t('authenticationCenter.org.hidNo')">
                  <span>{{ user.hidNo }}</span>
                </a-form-item>
                <a-form-item :label="$t('authenticationCenter.org.visibleApp')">
                  <span class="app-tag" v-for="app in appList" :key="app.id">
                    <a-avatar class="app-tag-icon" :size="20" :src="app.logo | imgURLFilter" />
                    {{ app.name }}
                  </span>
                  <span v-if="!loading && appList.length === 0">{{ hasAll ? '全部' : '无' }}</span>
                </a-form-item>
              </a-form>
            </div>
          </div>
          <div class="account-settings-info-right">
            <div class="avatar-wrap">
              <a-avatar class="avatar" :size="150" :src="user.avatar | imgURLFilter" />
            </div>
          </div>
        </div>
      </a-card>
    </a-spin>
  </div>
</template>

<script>
import { readUser, readAllOrg } from '@/api/organization'
import { readUserApps } from '@/api/authenticationCenter/structure'
import { layoutMixin } from '@/utils/mixin'
import { setArrayToTree } from '@/utils/util'
import { UserPickerOptions } from '@/components/UserPicker/options'

export default {
  name: 'AccountBaseInfo',
  mixins: [layoutMixin],
  data () {
    return {
      userId: null,
      user: {},
      form: this.$form.createForm(this),
      partyList: [],
      partyLoading: true,
      loading: false,
      // 从其它路由跳转过来还是直接打开
      routerCanBack: false,
      identityTypeMap: {
        NORMAL: 'authenticationCenter.org.normal',
        HIGHER: 'authenticationCenter.org.higher'
      },
      appList: [],
      hasAll: false
    }
  },
  computed: {
    // 部门全路径
    orgMatched () {
      console.log(this.user)
      if (!this.user || !this.user.orgIds || this.user.orgIds.length === 0) return []
      const orgMaps = []
      this.user.orgIds.forEach(id => {
        const tree = []
        let party = this.partyList.find(item => item.id === id)
        while (party) {
          tree.unshift(party)
          party = this.partyList.find(item => item.id === party[UserPickerOptions.pid])
        }
        const orgNames = tree.map(list => list.name).join('/')
        orgMaps.push({
          id,
          orgNames
        })
      })
      return orgMaps
    },
    manageOrgMatched () {
      if (!this.user || !this.user.orgIds || this.user.orgIds.length === 0 || !this.user.manageOrg) return []
      const orgMaps = []
      const regExp = new RegExp('(?<=\\[).*?(?=\\])', 'g')
      const manageOrgList = this.user.manageOrg.match(regExp).map(i => Number(i))
      manageOrgList.forEach(id => {
        const tree = []
        let party = this.partyList.find(item => item.id === id)
        while (party) {
          tree.unshift(party)
          party = this.partyList.find(item => item.id === party[UserPickerOptions.pid])
        }
        const orgNames = tree.map(list => list.name).join('/')
        orgMaps.push({
          id,
          orgNames
        })
      })
      return orgMaps
    }
  },
  mounted () {
    const vm = this
    Promise.all([this.getAllParty(), this.getUserInfo(), this.getUserApps()])
      .then(() => {
        vm.loading = false
      })
      .catch(() => {
        vm.loading = false
      })
  },
  methods: {
    // 编辑页获取用户信息
    async getUserInfo () {
      const { id } = this.$store.state.user.info
      this.userId = id

      const res = await readUser({ id })
      if (res.code === 'sso.ok') {
        const { avatar } = res.data
        this.user = { ...res.data }
      } else {
        this.handleBack()
      }
    },
    // 获取用户可见App
    async getUserApps () {
      const { id } = this.$store.state.user.info
      const res = await readUserApps({ userId: id })
      if (res.code === 'sso.ok') {
        this.hasAll = res.data.all
        if (res.data.all) return
        this.appList = res.data.list || []
      }
    },
    // 获取所有部门
    async getAllParty () {
      const res = await readAllOrg()
      if (res.code === 'sso.ok') {
        this.partyList = res.data || []
      }
      this.partyLoading = false
    },
    // 返回列表页面
    handleBack () {
      if (this.routerCanBack) {
        this.$router.back()
      } else {
        this.$router.push({ name: 'users' })
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    const fromRoute = from.name
    next(vm => {
      vm.routerCanBack = !!fromRoute
    })
  }
}
</script>

<style lang="less" scoped>
.account-settings-info-main {
  width: 100%;
  display: flex;
  height: 100%;
  overflow: auto;

  .account-settings-info-left {
    flex: 1;
    padding: 8px 40px;
    overflow: hidden;

    .account-settings-info-view {
      padding-top: 12px;
    }

    .org-name-tree {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }

  .account-settings-info-right {
    width: 224px;
    .avatar-wrap {
      text-align: center;
      .avatar {
        margin-bottom: 24px;
      }
    }
  }
}
</style>
